import json
import threading

import requests
import time
from PyQt5.QtCore import QObject, pyqtSlot, QMetaObject, Qt, pyqtSignal

import cache
from cache import Cache
from common.constant import Constant
from dao.commonDao import FriendApply, PullTime, Friend
from utils import httpUtil
from utils.transferUtil import TransferUtil


class ContactAction(QObject):

    #添加好友消息通知
    addFriendNotifySignal = pyqtSignal(str)

    #好友审核通知
    examineFriendNotifySignal = pyqtSignal(int,int)

    #好友列表刷新通知
    friendListRefreshSignal = pyqtSignal(str)

    def __init__(self):
        super().__init__()
        self.addFriendNotifySignal.connect(self.addFriendNotify)
        self.examineFriendNotifySignal.connect(self.examineFriendNotify)
        self.friendListRefreshSignal.connect(self.friendListRefresh)

    def addFriendNotify(self, notifyMsg):
        return notifyMsg

    def examineFriendNotify(self,userId,status):
        pass

    def friendListRefresh(self,listStr):
        pass

    @pyqtSlot()
    def openAddFriendView(self):
        QMetaObject.invokeMethod(Cache.app, 'createAddFriendView', Qt.QueuedConnection)

    @pyqtSlot(int,result=str)
    def getUserInfo(self,userId):
        '''
        本地查询某个用户信息
        :param userId:
        :return:
        '''
        friend = cache.Cache.dao.getFriendByUserId(userId)
        msg = TransferUtil.obj2DictWithout_(friend)
        msg.pop('metadata')
        return json.dumps(msg)

    @pyqtSlot(int,int,result=int)
    def examine(self,friendId,status):
        '''
        页面点击通过、拒绝好友申请
        :param friendId:
        :param status:
        :return:
        '''
        result = httpUtil.post('http://localhost:8080/walala-api/friend/examine',{'friendId':friendId,'status':status});
        if result is not None and result['code'] == 0:
            _thread = threading.Thread(target=self.sendExamineMsg(friendId,status))
            _thread.setDaemon(True)
            _thread.start()
            return 0;
        else:
            return -1;

    def sendExamineMsg(self,friendId,status):

        #发送审核结果消息给对方
        extra = {'status': status,'type':2}
        extraStr = json.dumps(extra)
        param = {'senderId': Cache.userInfo['id'], 'msgBody': '', 'receiverId': friendId,
                 'senderName': Cache.userInfo['username'], 'notifyType': 1,
                 'extra': extraStr, 'msgType': 1}
        httpUtil.postJson('http://localhost:8080/walala-api/message/notify',param)

        #更新好友列表
        self.updateFriendList(True)


    def receviedApply(self,notice):

        '''
        收到一条好友申请
        :param notice:
        :return:
        '''

        friendApply = FriendApply()
        friendApply.senderId = notice.senderId
        friendApply.receiverId = notice.receiverId
        friendApply.senderName = notice.senderName
        friendApply.msgBody = notice.msgBody
        friendApply.time = notice.time

        extraObj = json.loads(notice.extra)
        friendApply.status = extraObj['status']
        friendApply.extra = extraObj['extra']
        cache.Cache.dao.addFriendApply(friendApply)
        msg = TransferUtil.obj2DictWithout_(friendApply)
        msg.pop('metadata')
        self.addFriendNotifySignal.emit(json.dumps(msg))

    def examineApply(self,notice):
        extraObj = json.loads(notice.extra)
        status = extraObj['status']
        self.examineFriendNotifySignal.emit(notice.senderId,status)
        if status == 0:
            self.updateFriendList(True)


    def updateFriendList(self,whetherSendSignal):
        '''
        增量更新好友列表
        :param whetherSendSignal: 是否发送信号通知页面
        :return:
        '''
        pullTime = cache.Cache.dao.getPullTime('pull_friend')
        url = 'http://localhost:8080/walala-api/friend/list'
        if pullTime is None:
            now = int(round(time.time() * 1000))

            newTime = PullTime()
            newTime.id = Constant.pull_friend_time_type
            newTime.time = now
            cache.Cache.dao.addTime(newTime)
        else:
            url = url +'?lastTime=' + str(pullTime.time)

        friendList = httpUtil.get(url)
        if friendList is not None and friendList['data'] is not None:
            for friend in friendList['data']:
                exist = cache.Cache.dao.getFriendByUserId(friend['userId'])
                new = Friend()
                new.userId = friend['userId']
                new.remark = friend['remark']
                new.username = friend['username']
                new.avatar = friend['avatar']
                new.email = friend['email']
                new.phone = friend['phone']

                if exist is None:
                    cache.Cache.dao.addFriend(new)
                else:
                    cache.Cache.dao.updateFriend(new)
            if whetherSendSignal is True:
                self.friendListRefreshSignal.emit(json.dumps(friendList['data']))

    def pushfriendList(self):
        '''
        全量获取好友列表
        :return:
        '''
        print('好友列表调用')
        self.updateFriendList(False)
        list = cache.Cache.dao.getFriendList()
        result = []
        if list is not None:
            for friend in list:
                msg = TransferUtil.obj2DictWithout_(friend)
                msg.pop('metadata')
                result.append(msg)
            self.friendListRefreshSignal.emit(json.dumps(result))




